<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'order:m8OperCheck:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="50%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <h3>【订单号：{{ info.ccode }} 图号：{{ info.picno }} 图名：{{ info.picname }}】</h3>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsOrderM8OperCheckForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { checkForm, checksave } from '/@/api/m8/machine/machine';
  import { officeTreeData } from '/@/api/sys/office';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('order.m8OperCheck');
  const { showMessage } = useMessage();
  const record = ref<any>({});
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: '检验登记',
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('订单编号'),
      field: 'orderId',
      component: 'Input',
      dynamicDisabled: record.value['order.id'] ? true : false,
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('来源ID'),
      field: 'sourceId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('图纸编号'),
      field: 'picId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('流程ID'),
      field: 'flowId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('数铣ID'),
      field: 'sxId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('任务编号'),
      field: 'taskCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('来源工序'),
      field: 'operCode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('检验类型'),
      field: 'checkType',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'm8_check_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('工序类型'),
      field: 'operType',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'm8_oper_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('检验数量'),
      field: 'checkQty',
      component: 'InputNumber',
      dynamicDisabled: record.value.iqty == '1' ? true : false,
      componentProps: {
        maxlength: 8,
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('是否合格'),
      field: 'checkRs',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no',
        // allowClear: true,
      },
      required: true,
    },
    {
      label: t('下次巡检'),
      field: 'nextCheckDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      required: false,
    },
    {
      label: t('送检人'),
      field: 'sjManagerCode',
      fieldLabel: 'sjManagerName',
      component: 'TreeSelect',
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: true, userIdPrefix: '', isAll: true, isShowCode: true },
        immediate: true,
        canSelectParent: false,
        maxlength: 64,
      },
      required: true,
    },
    // {
    //   label: t('返工数量'),
    //   field: 'rsQty',
    //   component: 'Input',
    //   dynamicDisabled: true,
    //   componentProps: {
    //     maxlength: 8,
    //   },
    //   rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    // },
    // {
    //   label: t('报废数量'),
    //   field: 'bfQty',
    //   component: 'Input',
    //   dynamicDisabled: true,
    //   componentProps: {
    //     maxlength: 8,
    //   },
    //   rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    // },
    {
      label: t('不合格描述'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 1000,
      },
    },
    {
      label: t('不合格品处理数'),
      field: 'dealQty',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      ifShow: record.value.dealQty != 0 ? false : true,
    },
    {
      label: t('检验员'),
      field: 'jyManagerCodes',
      fieldLabel: 'jyManagerNames',
      component: 'TreeSelect',
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: true, userIdPrefix: '', isAll: true, isShowCode: true },
        immediate: true,
        canSelectParent: false,
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('附件上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'm8OperCheck_file',
        uploadType: 'image',
        maxSize: 100,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  let info = ref({
    ccode: '',
    picno: '',
    picname: '',
    checkStatus: '',
  });

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    console.log(data);
    await resetFields();
    const res = await checkForm(data);
    record.value = (res.m8TaskCheck || {}) as any;
    info.value.ccode = record.value.task.order.ccode;
    info.value.picno = record.value.task.orderPic.picno;
    info.value.picname = record.value.task.orderPic.picname;
    info.value.checkStatus = record.value.task.checkStatus;
    record.value.__t = new Date().getTime();
    if (record.value.checkType == '1') {
      record.value.checkQty = 1;
    }
    updateSchema([
      {
        field: 'checkType',
        componentProps: {
          disabled: true,
        },
      },
    ]);
    setFieldsValue(record.value);

    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        // isNewRecord: record.value.isNewRecord,
        // djNo: record.value.djNo,
        taskCode: record.value.task.taskCode,
        machineId: record.value.machineId,
      };
      let data1 = {
        ...data,
        taskCode: record.value.task.taskCode,
        machineId: record.value.machineId,
      };

      // console.log('submit', params, data, record);
      const res = await checksave(params, data1);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
